#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <pthread.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>

#include "cJSON.h"
#define ERR_MSG(msg) do{\
    fprintf(stderr,"__%s__,__%s__,__%d__",__FILE__,__func__,__LINE__);\
    perror(msg);\
}while(0)
#define N 64

#define IP "192.168.100.41" //"192.168.221.128"//"192.168.50.175""192.168.221.128"
#define PORT 1024
//需要传入到线程当中的参数
struct msg
{
    int newfd;
    struct sockaddr_in cin;
};


struct sockaddr_in addr;
int addrlen;
void* deal_cli_msg(void* arg);
int tcptransmit(void);
int main(int argc, char const *argv[])
{
    int broadfd;

    //创建一个socket文件描述符
    broadfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(broadfd < 0)
    {
        perror("sock err");
        return -1;
    }
    printf("listen success __%d__\n",__LINE__);
    //绑定套接字(ip+port)

    //允许端口快速被覆盖重用
    int reuse = 1;

    if(setsockopt(broadfd, SOL_SOCKET,SO_REUSEADDR, &reuse, sizeof(reuse)) <0)
    {
        ERR_MSG("setsockopt");
        return -1;
    }
    printf("允许端口快速被覆盖重用成功\n");
    
    addr.sin_family = AF_INET;
    addr.sin_port = htons(PORT);  //端口号
    addr.sin_addr.s_addr = INADDR_ANY;//任意IP：0.0.0.0
    addrlen = sizeof(addr);
    printf("listen success __%d__\n",__LINE__);
    if(bind(broadfd, (struct sockaddr *)&addr, addrlen) < 0)
    {
        perror("bind err");
        return -1;
    }
    printf("listen success __%d__\n",__LINE__);
    ssize_t len;
    char buf[N] = {0};
    struct sockaddr_in cliaddr;//#####################################################
    while (1)
    {
        //接收"coffee"搜索包
        bzero(buf, N);
        len = recvfrom(broadfd, buf, N, 0, (struct sockaddr *)&cliaddr, &addrlen);

        //判断是否是本公司产品：收到的数据是否"coffee"
        if(strcmp(buf, "coffee") != 0)
        {
            printf("not my coffee\n");
            return -1;
        }
        printf("listen success 收到数据coffee __%d__\n",__LINE__);
        //回复yes，告诉软件，我收到了搜索协议，并且回复地址
        sendto(broadfd, "yes", 4, 0, (struct sockaddr *)&cliaddr, addrlen);

        //***************************变身为TCP服务器，准备接收软件的升级文件***************************
        int tcpfd = socket(AF_INET, SOCK_STREAM, 0);
        if(tcpfd < 0)
        {
            perror("sock err");
            return -1;
        }
        printf("socket success sfd=%d\n",tcpfd);
        if(bind(tcpfd, (struct sockaddr *)&addr, addrlen) < 0)
        {
            perror("bind err");
            return -1;
        }
        printf("bind success __%d__\n",__LINE__);
        //监听套接字
        if(listen(tcpfd, 5) < 0)
        {
            perror("listen err");
            return -1;
        }
        printf("bind success __%d__\n",__LINE__);
        //接收客户端的连接
        printf("wait client connect\n");

        struct sockaddr_in cin;//存储客户端地址信息
        //socklen_t addrlen = sizeof(cin);
        addrlen = sizeof(cin);
        
        //int newfd = -1;
        pthread_t tid;
        struct msg info;

        while(1)
        {
                    //生成新的文件描述符与客户端通信
            int newfd = accept(tcpfd, (struct sockaddr*)&cin, &addrlen);
            if(newfd < 0)
            {
                ERR_MSG("accpt");
                return -1;
            }
            printf("[%s:%d] newfd=%d 客户端连接成功 __%d__\n",\
                    inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd,__LINE__);

                info.newfd = newfd;
                info.cin = cin;
                //创造线程
                if(pthread_create(&tid, NULL,deal_cli_msg, &info) != 0)
                {
                    fprintf(stderr,"pthread_create failed __%d__\n",__LINE__);
                }
                pthread_detach(tid);            //分离线程，线程退出后内核自动回收
        }    
                //关闭
                if(close(tcpfd) < 0)
                {
                    ERR_MSG("close");
                    return -1;
                }
    }
    printf("new cononect coming\n");    
    //close(broadfd);
    if(close(broadfd) < 0)
    {
        ERR_MSG("close");
        return -1;
    }
    return 0;
}
void *deal_cli_msg(void *arg)
{
    int newfd = ((struct msg *)arg)->newfd;
    struct sockaddr_in cin = ((struct msg *)arg)->cin;
    printf("newfd=%d\n", newfd);
    char buf[1024] = "";
    ssize_t res = 0;
    while (1)
    {
        bzero(buf, sizeof(buf));
        //接收
        res = recv(newfd, buf, sizeof(buf), 0);
        if (res < 0)
        {
            ERR_MSG("recv");
            break;
        }
        else if (0 == res)
        {
            printf("[%s:%d] newfd=%d客户端下线__%d__\n",
                   inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), newfd, __LINE__);

            break;
        }
        printf("[%s:%d] newfd=%d : %s __%d__\n",
               inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), newfd, buf, __LINE__);

        cJSON *root = NULL;
        root = cJSON_Parse(buf);
        if (NULL == root)
        {
            printf("parse err:%s\n", buf);
            return 0;
        }
        //获取ver节点
        char *sendbuf = NULL;
        int type = cJSON_GetObjectItem(root, "type")->valueint;
        printf("JSON success%d __%d__\n", type, __LINE__);
        if (type == 1)
        { //创建json树
            cJSON *ONE = cJSON_CreateObject();
            cJSON_AddNumberToObject(ONE, "type", 1);
            cJSON_AddNumberToObject(ONE, "result", 0);
            //判断是否有点表文件
            FILE *fd = fopen("./../dataReport/node.json", "r");
            printf("type == 1 success%d __%d__\n", type, __LINE__);
            if (fd == NULL) //需要下发
            {
                cJSON_AddNumberToObject(ONE, "up_config", 1);

                bzero(buf, strlen(buf));
                sendbuf = cJSON_Print(ONE);
                strcpy(buf, sendbuf);
                send(newfd, buf, strlen(buf), 0); //发送
                printf("type == 1需要下发 success%d __%d__\n", type, __LINE__);
            }
            else //不需要下发
            {

                cJSON *item_data = cJSON_CreateObject();
                cJSON *mqttConfig = cJSON_CreateObject();
                cJSON *videoConfig = cJSON_CreateObject();
                cJSON *updateConfig = cJSON_CreateObject();

                cJSON_AddItemToObject(ONE, "up_config", cJSON_CreateNumber(0)); //false
                cJSON_AddItemToObject(ONE, "data", item_data);
                cJSON_AddItemToObject(item_data, "mqtt_config", mqttConfig);
                cJSON_AddItemToObject(item_data, "video_config", videoConfig);
                cJSON_AddItemToObject(item_data, "updata_config", updateConfig);

                cJSON_AddStringToObject(mqttConfig, "mqtt_addr", "192.168.50.00");
                cJSON_AddNumberToObject(mqttConfig, "mqtt_port", 1883);

                cJSON_AddStringToObject(videoConfig, "video_addr", "192.168.31.244");
                cJSON_AddNumberToObject(videoConfig, "video_port", 502);

                cJSON_AddNumberToObject(updateConfig, "type", 2);
                cJSON_AddNumberToObject(updateConfig, "period", 2);
               
                bzero(buf, sizeof(buf));
                
                sendbuf = cJSON_PrintUnformatted(ONE);
                strcpy(buf, sendbuf);
               
                if (send(newfd, buf, strlen(buf), 0) < 0)
                {
                    ERR_MSG("send");
                    return 0;
                }
                printf("send success __%d__\n", __LINE__);
                printf("%s\n", buf);
                cJSON_Delete(ONE);
                printf("type == 1不需要下发 success%d __%d__\n", type, __LINE__);
            }
        }
        else if (type == 2)
        {
            cJSON *itemflagjson = NULL;
            printf("__%d__\n", __LINE__);
            itemflagjson = cJSON_GetObjectItem(root, "data");
            char itemflag[32] = {0};
            
            printf("__%d__%s\n", __LINE__,cJSON_GetObjectItem(itemflagjson, "flag")->valuestring);
            sprintf(itemflag, "%s", cJSON_GetObjectItem(itemflagjson, "flag")->valuestring);
            printf("__%d__%s\n", __LINE__,itemflag);
           
            printf("type == 2 success%d __%d__\n", type, __LINE__);
            if (!strcmp(itemflag, "start")) //准备接收
            {
               
                cJSON *TWO = cJSON_CreateObject();
                cJSON_AddNumberToObject(TWO, "type", 2);

                cJSON *two_data = cJSON_CreateObject();
                //cJSON *two_flag = cJSON_CreateObject();
                cJSON_AddItemToObject(TWO, "data", two_data);
                //cJSON_AddItemToObject(two_data, "flag", two_flag);
                cJSON_AddItemToObject(two_data, "flag", cJSON_CreateString("start"));

                bzero(buf, sizeof(buf));
                sendbuf = cJSON_Print(TWO);
                strcpy(buf, sendbuf);
                printf("start success%s __%d__\n",buf, __LINE__);
             
                if (send(newfd, buf, strlen(buf), 0) < 0)
                {
                    ERR_MSG("send");
                    return 0;
                }//准备接收
                 tcptransmit(); //接收端口
                printf("send success __%d__\n", __LINE__);
                cJSON_Delete(TWO);
                printf("type == 2  start success%d __%d__\n", type, __LINE__);
            }
            if (!strcmp(itemflag, "stop")) //接受完毕
            {
                 cJSON *TWO = cJSON_CreateObject();
                cJSON_AddNumberToObject(TWO, "type", 2);

                cJSON *two_data = cJSON_CreateObject();
                //cJSON *two_flag = cJSON_CreateObject();
                cJSON_AddItemToObject(TWO, "data", two_data);
                //cJSON_AddItemToObject(two_data, "flag", two_flag);
                cJSON_AddItemToObject(two_data, "flag", cJSON_CreateString("stop"));

                bzero(buf, sizeof(buf));
                sendbuf = cJSON_Print(TWO);
                strcpy(buf, sendbuf);
                //send(newfd,buf,sizeof(buf),0);
                if (send(newfd, buf, strlen(buf), 0) < 0)
                {
                    ERR_MSG("send");
                    return 0;
                }//接收完毕
            }
        }
        else if (type == 3)
        {
            printf("type == 3  start success%d __%d__\n", type, __LINE__);
            cJSON *three = cJSON_CreateObject();
            cJSON_AddNumberToObject(three, "type", 3);
            cJSON_AddNumberToObject(three, "result", 0);

            while (1)
            {
                sleep(2);
                bzero(buf, sizeof(buf));
                sendbuf = cJSON_Print(three);
                printf("链接正常：%s\n", sendbuf);
                strcpy(buf, sendbuf);
                send(newfd, buf, strlen(buf), 0); //发送
            }
            cJSON_Delete(three);
        }
    }
    if (close(newfd) < 0)
    {
        ERR_MSG("close");
        //return -1;
    }
    pthread_exit(NULL);
}
int tcptransmit(void)
{
    addr.sin_port = htons(1025);
    int tcpfd = socket(AF_INET, SOCK_STREAM, 0);
        if(tcpfd < 0)
        {
            perror("sock err");
            return -1;
        }
        printf("socket success sfd=%d\n",tcpfd);
        if(bind(tcpfd, (struct sockaddr *)&addr, addrlen) < 0)
        {
            perror("bind err");
            return -1;
        }
        printf("bind success __%d__\n",__LINE__);
        //监听套接字
        if(listen(tcpfd, 5) < 0)
        {
            perror("listen err");
            return -1;
        }
        printf("bind success __%d__\n",__LINE__);
        //接收客户端的连接
        printf("wait client connect\n");
        struct sockaddr_in cin; //存储客户端地址信息
        
        addrlen = sizeof(cin);

        //生成新的文件描述符与客户端通信
        int newfd = accept(tcpfd, (struct sockaddr *)&cin, &addrlen);
        if (newfd < 0)
        {
            ERR_MSG("accpt");
            return -1;
        }
        printf("[%s:%d] newfd=%d 客户端连接成功 __%d__\n",
               inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), newfd, __LINE__);

        char buf[4096] = "";
        ssize_t res = 0;
        bzero(buf, sizeof(buf));
        //************************接收*******************************
        res = recv(newfd, buf, sizeof(buf), 0);
        if (res < 0)
        {
            ERR_MSG("recv");
            return 0;
        }
        else if (0 == res)
        {
            printf("[%s:%d] newfd=%d客户端下线__%d__\n",\
                 inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd,__LINE__);
        }
        printf("__%d__\n", __LINE__);
        //buf
        printf("recv success __%d__\n",__LINE__);
        FILE *fd = fopen("./../dataReport/node.json", "w");
        if (fd == NULL)
        {
            printf("fd no__%d__\n", __LINE__);
        }
        printf("recv over %s __%d__\n",buf,__LINE__);
        //fgets(buf,strlen(buf),fd);
        fwrite(buf,res,1,fd);
        fclose(fd);
        printf("recv over __%d__\n",__LINE__);
        //关闭
        if (close(tcpfd) < 0)
        {
            ERR_MSG("close");
            return -1;
        }
        return 0;
}